var gulp = require('gulp');
var tap = require('gulp-tap');
var path = require('path');
var fs = require('fs');
var htmlmin = require('gulp-htmlmin');
var sass = require('gulp-sass');
var cleancss = require('gulp-clean-css');
var pump = require('pump');
var uglify = require('gulp-uglify');
var yargs = require('yargs').argv;
var browserSync = require('browser-sync').create();

var SRC = './src/';
var SRC_HTML = SRC + '**/*.html';
var SRC_SCSS = SRC + 'scss/**/*.scss';
var SRC_CSS = SRC + '*.css';
var SRC_JS = SRC + '*.js';

var BUILD = './build/';
var BUILD_HTML = BUILD + './';
var BUILD_CSS = BUILD + './';
var BUILD_JS = BUILD + './';

gulp.task('build:html', function () {
  gulp.src(SRC + 'index.html')
    .pipe(tap(function (file) {
      var dir = path.dirname(file.path);
      var contents = file.contents.toString();
      contents = contents.replace(/<link\s+rel="import"\s+href="(.*)">/gi, function (match, $1){
        var filename = path.join(dir, $1);
        var id = path.basename(filename, '.html');
        var content = fs.readFileSync(filename, 'utf-8');
        return '<script type="text/html" id="tpl-'+ id +'">\n'+ content +'\n</script>';
      });
      file.contents = new Buffer(contents);
    }))
    .pipe(htmlmin())
    .pipe(gulp.dest(BUILD_HTML))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('build:sass', function () {
  gulp.src(SRC_SCSS)
    .pipe(sass().on('error', function (e) {
      console.error(e.message);
      this.emit('end');
    }))
    .pipe(gulp.dest(SRC))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('build:css', ['build:sass'],  function () {
  gulp.src(SRC_CSS)
    .pipe(cleancss())
    .pipe(gulp.dest(BUILD_CSS))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('build:js', function () {
  var options = {
    preserveComments: 'license'
  };

  pump([
    gulp.src(SRC_JS),
    // uglify(options),
    gulp.dest(BUILD_JS),
    browserSync.reload({ stream: true })
  ]);
});

gulp.task('build', ['build:html', 'build:css', 'build:js']);

gulp.task('watch', ['build'], function () {
  gulp.watch(SRC_HTML, ['build:html']);
  gulp.watch(SRC_SCSS, ['build:css']);
  gulp.watch(SRC_JS, ['build:js']);
});

gulp.task('server', ['build'], function () {
  yargs.p = yargs.p || 8080;
  browserSync.init({
    server: {
      baseDir: "./build"
    },
    ui: {
      port: yargs.p + 1,
      weinre: {
        port: yargs.p + 2
      }
    },
    port: yargs.p,
    startPath: 'index.html'
  });
});

// 参数说明
//  -w: 实时监听
//  -s: 启动服务器
//  -p: 服务器启动端口，默认8080
gulp.task('default', ['build'], function () {
  if (yargs.s) {
    gulp.start('server');
  }

  if (yargs.w) {
    gulp.start('watch');
  }
});